package com.bym.mall.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * Aop配置类
 *
 * @author zhaoqiting
 * @date 2022/06/24
 */
@Slf4j
@Aspect
@Component
public class AopConfig {

    @Autowired
    private JavaMailSenderImpl mailSender;

    /**
     * 切点-时间成本记录
     */
    @Pointcut(value = "execution(* com.bym.mall.service..*.*(..))")
    public void timeCostRecordAspect() {
    }

    @Around("timeCostRecordAspect()")
    public Object recordSystemLog(ProceedingJoinPoint pjp) {
        //目标方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();

        //方法参数
        Object[] args = pjp.getArgs();

        long start = System.currentTimeMillis();
        Object response = null;
        try {
            response = pjp.proceed();
        } catch (Throwable e) {
            log.error("e:{}", e.getMessage(), e);
        } finally {
            long execTime = System.currentTimeMillis() - start;
            StringBuilder sb = new StringBuilder();
            sb.append("The time of the incident:").append(LocalDateTime.now()).append("\n")
                    .append("className:").append(className).append("\n")
                    .append("methodName:").append(methodName).append("\n")
                    .append("args:").append(Arrays.toString(args)).append("\n")
                    .append("response:").append(response).append("\n")
                    .append("execTime:").append(execTime).append(" ms").append("\n");
            String warnMsg = sb.toString();
            if (execTime > 2000) {
                log.warn(warnMsg);
                //发送邮件给应用管理员
                /*SimpleMailMessage mail = new SimpleMailMessage();
                mail.setSubject("Server Error!!!");
                mail.setText(warnMsg);
                mail.setTo("19883136690@163.com");
                mail.setFrom("19883136690@163.com");
                mailSender.send(mail);*/
            } else {
                log.info(warnMsg);
            }
        }

        return response;
    }
}
